<template>
  <div class="app-container">
    <div class="filter-container">
      <el-input v-model="listQuery.roleName" :placeholder="$t('角色名')" style="width: 200px;" class="filter-item" @keyup.enter.native="handleFilter" />
      <el-button v-if="$store.getters.button.includes('system:role:search')" v-waves class="filter-item" type="primary" icon="el-icon-search" @click="handleFilter">
        {{ $t('table.search') }}
      </el-button>
      <el-button v-if="$store.getters.button.includes('system:role:add')" class="filter-item" style="margin-left: 10px;" type="primary" icon="el-icon-edit" @click="handleCreate">
        {{ $t('table.add') }}
      </el-button>
    </div>
    <el-table
      :key="tableKey"
      v-loading="listLoading"
      :data="list"
      element-loading-text="请稍后..."
      border
      fit
      highlight-current-row
      style="width: 100%;"
      @sort-change="sortChange"
    >
      <el-table-column :label="$t('table.id')" prop="id" sortable="custom" align="center" width="80" :class-name="getSortClass('id')" show-overflow-tooltip>
        <template slot-scope="{row}">
          <span>{{ row.id }}</span>
        </template>
      </el-table-column>
      <el-table-column :label="$t('角色名')" min-width="50px" align="center" show-overflow-tooltip>
        <template slot-scope="{row}">
          <span>{{ row.roleName }}</span>
        </template>
      </el-table-column>
      <el-table-column :label="$t('角色值')" min-width="50px" align="center" show-overflow-tooltip>
        <template slot-scope="{row}">
          <span>{{ row.rval }}</span>
        </template>
      </el-table-column>
      <el-table-column :label="$t('状态')" class-name="status-col" min-width="30">
        <template slot-scope="{row}">
          <span v-if="row.status==0" style="color: limegreen;">启用</span>
          <span v-else style="color: red;">禁用</span>
        </template>
      </el-table-column>
      <el-table-column :label="$t('创建时间')" min-width="50px" align="center" show-overflow-tooltip>
        <template slot-scope="{row}">
          <span>{{ row.createTime | parseTime('{y}-{m}-{d} {h}:{i}') }}</span>
        </template>
      </el-table-column>

      <el-table-column :label="$t('table.actions')" align="center" width="210px" class-name="small-padding fixed-width">
        <template slot-scope="{row,$index}">
          <el-button v-if="$store.getters.button.includes('system:role:edit')" type="primary" size="mini" @click="handleUpdate(row)">
            {{ $t('table.edit') }}
          </el-button>
          <el-button v-if="$store.getters.button.includes('system:role:delete')" size="mini" type="danger" @click="handleDelete(row,$index)">
            {{ $t('table.delete') }}
          </el-button>
        </template>
      </el-table-column>
    </el-table>
    <pagination v-show="total>0" :total="total" :page.sync="listQuery.page" :limit.sync="listQuery.limit" @pagination="getList" />

    <el-dialog :title="textMap[dialogStatus]" :visible.sync="dialogFormVisible">
      <el-form ref="dataForm" :rules="rules" :model="temp" label-position="left" label-width="70px" style="width: 400px; margin-left:50px;">
        <el-form-item :label="$t('角色名')" prop="roleName">
          <el-input v-model="temp.roleName" />
        </el-form-item>
        <el-form-item :label="$t('角色值')" prop="rval">
          <el-input v-model="temp.rval" />
        </el-form-item>
        <el-form-item :label="$t('状态')">
          <el-select v-model="temp.status" placeholder="请选择">
            <el-option
              v-for="item in options"
              :key="item.value"
              :label="item.label"
              :value="item.value"
            />
          </el-select>
        </el-form-item>
        <el-form-item :label="$t('描述')">
          <el-input v-model="temp.description" :autosize="{ minRows: 2, maxRows: 4}" type="textarea" placeholder="Please input" />
        </el-form-item>
        <el-form-item :label="$t('角色权限')">
          <tree
            :setting="setting"
            :nodes="treePermission"
            class="treeClass"
            @onCreated="handleCreated"
          />
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="dialogFormVisible = false">
          {{ $t('table.cancel') }}
        </el-button>
        <el-button type="primary" @click="dialogStatus==='create'?createData():updateData()">
          {{ $t('table.confirm') }}
        </el-button>
      </div>
    </el-dialog>

    <el-dialog :visible.sync="dialogPvVisible" title="Reading statistics">
      <el-table :data="pvData" border fit highlight-current-row style="width: 100%">
        <el-table-column prop="key" label="Channel" />
        <el-table-column prop="pv" label="Pv" />
      </el-table>
      <span slot="footer" class="dialog-footer">
        <el-button type="primary" @click="dialogPvVisible = false">{{ $t('table.confirm') }}</el-button>
      </span>
    </el-dialog>
  </div>
</template>

<script>
import waves from '@/directive/waves' // waves directive
import { parseTime } from '@/utils'
import tree from 'vue-giant-tree'
import Pagination from '@/components/Pagination' // secondary package based on el-pagination
import { getsysMenuList, getmenuRoles, addRole, getListPage, deleteRole } from '@/api/role'

export default {
  name: 'RolesTable',
  components: { Pagination, tree },
  directives: { waves },  
  data() {
    return {
      tableKey: 0,
      list: null,
      total: 0,
      listLoading: true,
      listQuery: {
        page: 1,
        limit: 20,
        roleName: ''
      },
      options: [{
        value: 0,
        label: '启用'
      }, {
        value: 1,
        label: '禁用'
      }],
      // ztree数据
      treePermission: [],
      // ztree对象
      ztreeObj: null,
      // ztree配置，参照ztree官网的配置
      setting: {
        check: {
        // 树是否带复选框或者单选框
          enable: true
        },
        data: {
          key: {
            name: 'name'
          },
          simpleData: {
            // 是否使用简单数据模式
            enable: true,
            // 树节点id，一般是后台数据库主键
            idKey: 'id',
            // 父级id
            pIdKey: 'pid',
            rootPId: 0
          }
        }
      },
      temp: {
        id: undefined,
        roleName: '',
        rval: '',
        description: '',
        status: 0
      },
      dialogFormVisible: false,
      dialogStatus: '',
      textMap: {
        update: '修改',
        create: '添加'
      },
      dialogPvVisible: false,
      pvData: [],
      rules: {
        roleName: [{ required: true, message: '角色名不能为空', trigger: 'blur' }],
        rval: [{ required: true, message: '角色值不能为空', trigger: 'blur' }]
      }
    }
  },
  created() {
    this.getList()
  },
  methods: {
    getList() {
      this.listLoading = true
      getListPage(this.listQuery).then(response => {
        this.list = response.data.list
        this.total = response.data.total
        setTimeout(() => {
          this.listLoading = false
        }, 1.5 * 1000)
      })
    },
    initRole() {
      getsysMenuList().then(response => {
        this.treePermission = response.data || []
        this.selectDefault()
      })
    },
    selectDefault() {
      if (this.temp.id) {
        getmenuRoles(this.temp).then(response => {
          let tag = true
          while (tag) {
            if (this.ztreeObj != null) {
              response.data.menu.forEach(item => {
                const node = this.ztreeObj.getNodeByParam('id', item)
                this.ztreeObj.checkNode(node)
              })
              tag = false
            }
          }
        })
      }
    },
    handleCreated: function(ztreeObj) {
      this.ztreeObj = ztreeObj
      // onCreated 中操作ztreeObj对象展开第一个节点
      ztreeObj.expandNode(ztreeObj.getNodes()[0], true)
      const ztreeNodes = ztreeObj.getNodes()[0].children
      ztreeNodes.find(treeNode => {
        if (treeNode.type === '***') {
          ztreeObj.setChkDisabled(treeNode, true)
        }
      })
    },
    handleFilter() {
      this.listQuery.page = 1
      this.getList()
    },
    sortChange(data) {
      const { prop, order } = data
      if (prop === 'id') {
        this.sortByID(order)
      }
    },
    sortByID(order) {
      if (order === 'ascending') {
        this.listQuery.sort = '+id'
      } else {
        this.listQuery.sort = '-id'
      }
      this.handleFilter()
    },
    resetTemp() {
      this.temp = {
        id: undefined,
        roleName: '',
        rval: '',
        description: '',
        status: 0
      }
    },
    handleCreate() {
      this.resetTemp()
      this.dialogStatus = 'create'
      this.dialogFormVisible = true
      this.$nextTick(() => {
        this.$refs['dataForm'].clearValidate()
      })
      this.initRole()
    },
    createData() {
      this.$refs['dataForm'].validate((valid) => {
        if (valid) {
          const checked = this.ztreeObj.getCheckedNodes(true)
          const subData = {
            id: undefined,
            roleName: this.temp.roleName,
            rval: this.temp.rval,
            status: this.temp.status,
            description: this.temp.description,
            menu: []
          }
          if (checked && checked.length > 0) {
            checked.forEach(item => {
              subData.menu.push(item.id)
            })
          }
          addRole(subData).then(() => {
            this.list.unshift(subData)
            this.dialogFormVisible = false
            this.getList()
            this.$notify({
              title: '成功',
              message: '创建成功',
              type: 'success',
              duration: 2000
            })
          })
        }
      })
    },
    handleUpdate(row) {
      this.temp = Object.assign({}, row) // copy obj
      this.dialogStatus = 'update'
      this.dialogFormVisible = true
      this.$nextTick(() => {
        this.$refs['dataForm'].clearValidate()
      })
      this.initRole()
    },
    updateData() {
      this.$refs['dataForm'].validate((valid) => {
        if (valid) {
          const checked = this.ztreeObj.getCheckedNodes(true)
          const subData = {
            id: this.temp.id,
            roleName: this.temp.roleName,
            rval: this.temp.rval,
            status: this.temp.status,
            description: this.temp.description,
            menu: []
          }
          if (checked && checked.length > 0) {
            checked.forEach(item => {
              subData.menu.push(item.id)
            })
          }
          addRole(subData).then(() => {
            const index = this.list.findIndex(v => v.id === this.temp.id)
            this.list.splice(index, 1, this.temp)
            this.dialogFormVisible = false
            this.$notify({
              title: '成功',
              message: '更新成功',
              type: 'success',
              duration: 2000
            })
          })
        }
      })
    },
    handleDelete(row, index) {
      deleteRole(row).then(() => {
        this.$notify({
          title: '成功',
          message: '删除成功',
          type: 'success',
          duration: 2000
        })
      })
      this.list.splice(index, 1)
    },
    formatJson(filterVal) {
      return this.list.map(v => filterVal.map(j => {
        if (j === 'timestamp') {
          return parseTime(v[j])
        } else {
          return v[j]
        }
      }))
    },
    getSortClass: function(key) {
      const sort = this.listQuery.sort
      return sort === `+${key}` ? 'ascending' : 'descending'
    }
  }
}
</script>
